<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Admin/classes/PhpFox_ComponentMysqlMaintenance.class.php, $Author:  $ */

/** Component for optimization mysql tables
 *
 * @version $Id: PhpFox_ComponentMysqlMaintenance.class.php 442 2008-04-22 16:10:07Z phpfoxsv $
 * @package module.admin
 */
class PhpFox_Mod_Admin_ComponentMysqlMaintenance extends BaseComponent
{
	function getSqlDumb($sTable)
	{
		$sDumpDetails = $this->oDatabase->getRow("SHOW CREATE TABLE $sTable");
		$sDump = "DROP TABLE IF EXISTS $sTable;\n" . $sDumpDetails['Create Table'] . ";\n\n";

		$aRows = $this->oDatabase->getRows("SELECT * FROM $sTable");
		foreach($aRows as $aRow)
		{
			$sDump .= "INSERT INTO $sTable VALUES(";
			$i = 0;
			foreach($aRow as $a => $b)
			{
				$i++;
				$sDump .= ($i != 1 ? ', ' : '') . (empty($b) ? ($b == '0' ? "'0'" : "'0'") : "'" . $this->oDatabase->escape($b) . "'");
			}

			$sDump .= ");\n";
		}

		return $sDump;
	}

    function process()
    {
        $oAdminService = $this->_oModule->getService('Admin');
        /* @var $oAdminService PhpFox_Mod_Admin_ServiceAdmin */
        $oTpl = &$this->_oModule->getTemplate();
        $oReq = &App::getRequest();
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        if (!$oSecurityService->hasStaffPerm('MENU_mysql'))
        {
            App::gotoUrl('admin.main');
        }

		$sBackupPath = rtrim(App::getParam('backup_path'), "/") . "/";

		if ( $oReq->get('download') )
		{
			$aTables = $oReq->getArray('tables');
			
			$sTables = '';
			foreach ($aTables as $sTable)
			{
				$sTables .= $sTable . ' ';	
			}

			$sFileName = App::getParam('path') . 'file/backups/phpfox-db-backup.sql';
			@unlink($sFileName);
			
			// /opt/lampp/bin/
			@exec("mysqldump --skip-add-locks --disable-keys --skip-comments -h". App::getParam('db','host') ." -u". App::getParam('db','user') ." -p". App::getParam('db','pass') ." ". App::getParam('db','name') ." " . $sTables . " > " . $sFileName);
			@exec("tar -czf ". $sFileName .".tar.gz $sFileName");
			
			@unlink($sFileName);
			
			header('Location: ' . App::getParam('url') . 'file/backups/phpfox-db-backup.sql.tar.gz');
			exit;
					
			if ( count($aTables) > 0 )
			{
				@ob_clean();
				@ob_start();
				@ob_clean();

				print "\r\n### phpFoX Database Backup Complete :: ". date("F j, Y, g:i a", time()) ." ###\r\n\r\n\r\n";
				foreach($aTables as $sTable)
				{
					print $this->getSqlDumb($sTable);
					print "\n\n\n";
					@ob_flush();
				}
				print "\r\n### phpFoX Database Backup Complete ###";
				$sStr = ob_get_contents();

				@ob_clean();

				if ( eregi("phpFoX Database Backup Complete", $sStr) )
				{
					header('Content-disposition: attachment; filename=phpfox'. time() .'.sql');
					header('Content-type: unknown/unknown');
					print $sStr;
					exit;
				}
				@ob_end_flush();
			}
		}

		if ( $oReq->get('save') )
		{
			if ( !is_writable($sBackupPath) )
			{
				$sCachedMessages = App::format('admin.backup.perm', $sBackupPath);
			}
			else
			{
				if ( function_exists("exec") AND $checkDump = @str_replace("mysqldump:","",exec("whereis mysqldump")) AND !empty($checkDump) )
				{
					$sFile = str_replace('.tar.gz', '', $oReq->get('file'));					
					$filename = $sFile . ".sql";
					@exec("mysqldump --skip-add-locks --disable-keys --skip-comments -h". App::getParam('db','host') ." -u". App::getParam('db','user') ." -p". App::getParam('db','pass') ." ". App::getParam('db','name') ." >". $filename ."");
					$sZipName = $sFile . ".tar.gz";
					$zipline = "tar -czf ". $sZipName ." $filename";
					@shell_exec($zipline);
					@unlink($filename);
					if ( file_exists($sZipName) )
					{
						@unlink($filename);
						$sCachedMessages = App::format('admin.created.backup', $sZipName);
					}
					else
					{
						$sCachedMessages = App::format('admin.backup.file');
					}
				}
				else
				{
					$sCachedMessages = App::format('admin.backup.non.linux');
				}
			}
			App::gotoUrl('admin.extra.mysql', array('backup' => 'true'), $sCachedMessages, false);
		}

        $iOptimized = 0;
        if ($oReq->getAction() == 'optimize')
        {
            $aTables = $oReq->getArray('tables');
            if (!$iOptimized = count($aTables))
            {
                App::gotoUrl('admin.extra.mysql');
            }
            foreach ($aTables as $sTable)
            {
                $oAdminService->optimizeTable($sTable);
            }
        }

        $iRepair = 0;
        if ($oReq->getAction() == 'repair')
        {
            $aTables = $oReq->getArray('tables');
            if (!$iRepair = count($aTables))
            {
                App::gotoUrl('admin.extra.mysql');
            }
            foreach ($aTables as $sTable)
            {
                $oAdminService->repairTable($sTable);
            }
        }

        $aItems = $oAdminService->getTableStatus();
        $iSize = 0;
        $iOverhead = 0;
        foreach ($aItems as $iKey => $aItem)
        {
            if ($aItems[$iKey]['Name'] == App::getParam('db', 'prefix') . 'online_session')
            {
            	unset($aItems[$iKey]);
            	continue;
            }
        	$iSize += $aItem['Data_length'];
            $iOverhead += $aItem['Data_free'];
           	$aItems[$iKey]['Name'] = $aItems[$iKey]['Name'];
        }
        $oTpl->assign(array(
            'aItems'     => $aItems,
            'iOptimized' => $iOptimized,
            'iRepair' => $iRepair,
            'iCnt'       => count($aItems),
            'iSize'      => $iSize,
            'iOverhead'  => $iOverhead,
            'sSavedFile' => $sBackupPath . App::getParam('db','name') . date('mdy-hia') . '_sql.tar.gz'
        ));
        return $oTpl->fetch('MysqlMaintenance.html');
    }
}
?>